import Taro from '@tarojs/taro'
import {
  call, put, all, takeLatest, select
} from 'redux-saga/effects'
import {
  GLOBAL_SEARCH, SET_SEARCH_HISTORY, CLEAR_SEARCH_HISTORY, INITIAL_SEARCH_HISTORY
} from '@ACTIONS/search'
import api from '@API'
import { SEARCH_TYPE } from '@CONSTANTS/search'
import {
  getSearchDoctor, getSearchFeed, getSearchCourse, getRefreshHistory
} from './dataSelect'

export const DEFAULT_TAKE = 10
const SEARCH_HISTORY = 'searchHistory'

const getSearchData = {
  [SEARCH_TYPE.Doctor]: getSearchDoctor,
  [SEARCH_TYPE.FeedItem]: getSearchFeed,
  [SEARCH_TYPE.Course]: getSearchCourse,
}

const initSearchHistory = function* initSearchHistory() {
  yield call(setSearchHistory)
}

const setSearchHistory = function* setSearchHistory(st) {
  try {
    let searchHistory = Taro.getStorageSync(SEARCH_HISTORY) || []
    if (st !== undefined) {
      searchHistory = searchHistory.filter(item => item !== st)
      searchHistory.unshift(st)
      Taro.setStorageSync(SEARCH_HISTORY, searchHistory)
    }
    const refreshFlag = yield select(getRefreshHistory)
    yield put({ type: SET_SEARCH_HISTORY.SUCCESS, refreshHistory: !refreshFlag })
  } catch (error) {
    yield put({ type: SET_SEARCH_HISTORY.FAILURE, error })
  }
}

const clearSearchHistory = function* clearSearchHistory(action) {
  try {
    const { index } = action
    const searchHistory = Taro.getStorageSync(SEARCH_HISTORY)
    let newSearchHistory = []
    if (index !== undefined) {
      newSearchHistory = [...searchHistory]
      newSearchHistory.splice(index, 1)
    }
    const refreshFlag = yield select(getRefreshHistory)
    Taro.setStorageSync(SEARCH_HISTORY, newSearchHistory)
    yield put({ type: SET_SEARCH_HISTORY.SUCCESS, refreshHistory: !refreshFlag })
  } catch (error) {
    yield put({ type: CLEAR_SEARCH_HISTORY.FAILURE, error })
  }
}

const globalSearch = function* globalSearch(action) {
  const { params = {} } = action
  const { searchType, skip, st } = params
  try {
    const getData = getSearchData[searchType] || getSearchFeed
    const searchData = yield select(getData)
    const realSkip = skip === 0 ? 0 : searchData.length
    if (st !== '') {
      yield call(setSearchHistory, st)
    }
    const result = yield call(api.globalSearch, {
      ...params,
      skip: realSkip,
      take: DEFAULT_TAKE,
      type: searchType,
    })
    yield put({
      type: GLOBAL_SEARCH.SUCCESS, result, searchType, skip: realSkip
    })
  } catch (error) {
    yield put({ type: GLOBAL_SEARCH.FAILURE, searchType })
  }
}

export default function* rootSaga() {
  yield all([
    takeLatest(GLOBAL_SEARCH.REQUEST, globalSearch),
    takeLatest(SET_SEARCH_HISTORY.REQUEST, setSearchHistory),
    takeLatest(INITIAL_SEARCH_HISTORY.REQUEST, initSearchHistory),
    takeLatest(CLEAR_SEARCH_HISTORY.REQUEST, clearSearchHistory),
  ])
}
